package cn.vire.electric.simulation.config.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.Arrays;
import java.util.List;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        //注意，此处要过滤到swagger在线文档，然后正常接口的请求过滤时不要加.yml配置文件中的server.servlet.context-path 的路径，否则过滤不生效
        String[] excludePatterns = new String[]{"/swagger-resources/**","/static/**","/favicon.ico","/webjars/**", "/v2/**", "/img/icons/**", "/doc.html/**", "/user/jump-login"};
        List<String> urls = Arrays.asList(excludePatterns);

        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**")
                .excludePathPatterns(urls);
        super.addInterceptors(registry);
    }

    //重新资源头，解决拦截swagger问题
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/img/icons/**")
                .addResourceLocations("classpath:/META-INF/resources/img/icons/");
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/");
    }
}
